/**
 * 获取验证码
 */
import query from '../../untils/mysql';
import * as uuid from 'uuid';
import { Tip } from '../../untils/untils';
import { check, validationResult } from 'express-validator';
import { testing } from '../../untils/validator';

const validator = [
    check('phone').custom((val) => {
        if (!testing.isPhone(val)) {
            throw new Error('手机号格式有误');
        } else {
            return val
        }
    })
]
const POST = async (req: any, res: any, next: any) => {
    try {
        const { phone } = req.body;
        var errors = validationResult(req);
        if (!errors.isEmpty()) {
            return Tip.tipError(res, errors.array()[0].msg);
        }
        const resPhone = await query(`select phone from code where phone = '${phone}'`);
        let code = '123456';
        var data;
        if (resPhone.length) {
            data = await query(`update code set code = '${code}' where phone = '${phone}'`);
        } else {
            data = await query(`insert into code (id,phone,code) values ('${uuid.v1()}','${phone}',${code})`);
        }
        return Tip.tipSuccess(res, '下发成功', data)
    } catch (error: any) {
        Tip.tipError500(res, error)
    }
}

export {
    POST,
    validator
}